package com.sky.service.user.Impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;

import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserLoginMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;

import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {


    private final static String URL = "https://api.weixin.qq.com/sns/jscode2session"; //定义常量 路径  小程序提供的请求url HTTPS 调用

    @Value("${sky.wechat.appid}")  //${sky.wechat.appid}" 找到配置类文件
    private String appId;
    @Value("${sky.wechat.secret}")
    private String secret;

    @Autowired
    private UserLoginMapper userLoginMapper;//登录

    @Autowired
    private JwtProperties jwtProperties; //JwtProperties生成jwt令牌相关配置

    @Autowired
    private MerchantMapper merchantMapper;//商家信息


    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        //用户微信登录，完成自动注册

        //1.要去微信端获取openid  （来自私有方法获取的openId）
        String openId = getOpenId(dto.getCode());  //微信的唯一标识
        if (!StringUtils.hasText(openId))  //判断字符串是否存在
        {
            throw new BaseException("未获取到openId");
        }
        //2.根据openid去数据库查询
        User user = userLoginMapper.getOpenId(openId);
        //3.不存在就保存openid
        if (user == null) {
            user = new User();
            user.setCreateTime(LocalDateTime.now());//设置数据库需要的数据
            user.setOpenid(openId);
            //插入一条用户信息  参数为user
            userLoginMapper.addUserOpenID(user);
        }
        //4.拿着openid生成token
        {
            HashMap<String, Object> param = new HashMap<>();
            log.info("openId{},userId{}", openId, user.getId());
            param.put("openId", openId);
            param.put("userId", user.getId());

            String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), param);//注入
            log.info("token:{}", token);
            //获取商家信息 1号商家信息
            Merchant shangJia = merchantMapper.getShopId(1L);
            //计算费用
            String lnglat = MapUtils.addressToLnglat(shangJia.getShopAddress());
            log.info("调用工具类获取商家经纬度{}", lnglat);
            log.info("用户的经纬度{}", dto.getTelephone());
            BigDecimal jiaGe = MapUtils.getDelivoryCost(lnglat, dto.getLocation());  //费用类型用BigDecimal  避免精度丢失
            log.info("调用工具类计算距离，商家的经纬度{}，用户的经纬度{}", lnglat, dto.getTelephone());
            log.info("用户的经纬度{}", dto.getTelephone());

            log.info("计算出的价格是{}", jiaGe);



            //5。构造返回结果
            UserLoginVO userLoginVO = new UserLoginVO();
            userLoginVO.setToken(token);
            userLoginVO.setOpenid(openId);
            userLoginVO.setDeliveryFee(jiaGe);//配送费
            userLoginVO.setShopAddress(shangJia.getShopAddress());//商家位置
            userLoginVO.setShopId(shangJia.getId());//商家id
            userLoginVO.setShopName(shangJia.getShopName());
            userLoginVO.setShopTelephone(shangJia.getShopTelephone());

            log.info("配送费设置{}", jiaGe);
            log.info("商家位置{}", shangJia.getShopAddress());
            log.info("商家id{}", shangJia.getShopName());
            log.info("商家名字{}", shangJia.getShopAddress());
            log.info("商家位置电话{}", shangJia.getShopTelephone());

            return userLoginVO;
        }
    }

    /**
     * 获取openid
     *
     * @param code
     * @return
     */
    private String getOpenId(String code) {

        HashMap<String, String> Param = new HashMap<>();//发送请求需要提供map

        //参数设置 来自小程序接口
        Param.put("appid", appId);//小程序管理员的appid 参数appId在我的dev.yml中配置好了
        Param.put("secret", secret);//管理员的小程序的私钥，在我的dev.yml中已配置
        Param.put("js_code", code); //请求参数传入的参数（来自登录小程序返回的code）
        Param.put("grant_type", "autoorization_code"); //固定写死（来自小程序接口）

        log.info("参数设置code#{}", code);
        //发送请求  得到json串
        String respose = HttpClientUtil.doGet(URL, Param);
        log.info("微信登录返回：{}", respose);

        //工具类 格式转换         json字符串 转json对象
        JSONObject jsonObject = JSONObject.parseObject(respose);
        String openid = (String) jsonObject.get("openid");
        return openid;
    }
}